// 产品交付上传组件
import React, { useState, useEffect, useCallback } from 'react'
import useStore from '../../components/useStore'
import { Button, DatePicker, Divider, Form, Input, Modal, Spin, Upload, notification, Row, Col, Radio, Table, Select } from 'antd'
import { UploadOutlined, createFromIconfontCN, LinkOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'
import request from '../../untils/request.js'

const { Option } = Select;

// 自定义图标
const IconFont = createFromIconfontCN({
  scriptUrl: require('../../../devDocument/icon.js'),
});

const ProductDeliveryUploadOrder = () => { 
    const { collapsed, setnowroute } = useStore()
    const [form] = Form.useForm()
    
    // 文件上传状态
    const [deliveryListFile, setDeliveryListFile] = useState(null)
    const [factoryAcceptanceReportFile, setFactoryAcceptanceReportFile] = useState(null)
    const [shipmentPlanFile, setShipmentPlanFile] = useState(null)
    const [productShipmentOrderFile, setProductShipmentOrderFile] = useState(null)
    const [customerAcceptanceReportFile, setCustomerAcceptanceReportFile] = useState(null)
    const [uploading, setUploading] = useState(false)
    
    // 加载状态
    const [loadingProducts, setLoadingProducts] = useState(false)
    const [loadingCustomer, setLoadingCustomer] = useState(false)
    const [loadingStations, setLoadingStations] = useState(false); // 站点加载状态
    const [loadingSalesOrders, setLoadingSalesOrders] = useState(false); // 销售单号加载状态
    
    // 数据状态
    const [customerName, setCustomerName] = useState('')
    const [duplicateSn, setDuplicateSn] = useState([])
    const [invalidProductPairs, setInvalidProductPairs] = useState([])
    const [stations, setStations] = useState([]); // 当前客户的站点列表（包含station_id和名称）
    const [salesOrderOptions, setSalesOrderOptions] = useState([]); // 可选销售单号列表

    // 上传方式状态
    const [deliveryListUploadType, setDeliveryListUploadType] = useState('file')
    const [factoryReportUploadType, setFactoryReportUploadType] = useState('file')
    const [shipmentPlanUploadType, setShipmentPlanUploadType] = useState('file')
    const [productOrderUploadType, setProductOrderUploadType] = useState('file')
    const [customerReportUploadType, setCustomerReportUploadType] = useState('file')

    // 产品列表按信息完整性分类
    const [completeProducts, setCompleteProducts] = useState([]); // SN和station_id都有
    const [incompleteProducts, setIncompleteProducts] = useState([]); // SN和station_id都无

    // 防抖计时器
    const [debounceTimer, setDebounceTimer] = useState(null);

    // 检测重复SN码
    const checkDuplicateSn = (list) => {
        const sns = list.map(item => item.sn?.trim()).filter(sn => sn);
        const duplicates = sns.filter((sn, index) => sns.indexOf(sn) !== index);
        setDuplicateSn([...new Set(duplicates)]);
        return duplicates.length > 0;
    }

    // 检查SN与station_id一致性（使用station_id）
    const checkSnSiteConsistency = (list) => {
        const invalidProducts = list
            .filter(item => (!!item.sn?.trim() && !item.station_id) || (!item.sn?.trim() && !!item.station_id))
            .map(item => `产品ID: ${item.id} (${item.product_part_number})`);
            
        setInvalidProductPairs(invalidProducts);
        return invalidProducts.length === 0;
    }

    // 完整信息产品列定义（使用station_id）
    const completeProductColumns = [
        {
            title: '产品料号',
            dataIndex: 'product_part_number',
            key: 'product_part_number',
            width: '25%',
            render: (text) => <div style={{ padding: '4px 0', color: '#333' }}>{text || '-'}</div>
        },
        {
            title: '规格型号',
            dataIndex: 'specification_and_model',
            key: 'specification_and_model',
            width: '25%',
            render: (text) => <div style={{ padding: '4px 0', color: '#333' }}>{text || '-'}</div>
        },
        {
            title: 'SN码',
            dataIndex: 'sn',
            key: 'sn',
            width: '25%',
            render: (text) => (
                <div style={{ padding: '8px 12px', backgroundColor: '#f5f5f5', borderRadius: '4px', color: '#555', border: '1px solid #e8e8e8' }}>
                    {text}
                </div>
            )
        },
        {
            title: '站点ID',
            dataIndex: 'station_id',
            key: 'station_id',
            width: '25%',
            render: (stationId) => {
                // 显示站点ID和名称
                const station = stations.find(s => s.id === stationId);
                return (
                    <div style={{ padding: '8px 12px', backgroundColor: '#f5f5f5', borderRadius: '4px', color: '#555', border: '1px solid #e8e8e8' }}>
                        {stationId} {station ? `(${station.name})` : ''}
                    </div>
                )
            }
        }
    ];

    // 待完善产品列定义（使用station_id）
    const incompleteProductColumns = [
        {
            title: '产品料号',
            dataIndex: 'product_part_number',
            key: 'product_part_number',
            width: '20%',
            render: (text) => <div style={{ padding: '4px 0', color: '#333' }}>{text || '-'}</div>
        },
        {
            title: '规格型号',
            dataIndex: 'specification_and_model',
            key: 'specification_and_model',
            width: '20%',
            render: (text) => <div style={{ padding: '4px 0', color: '#333' }}>{text || '-'}</div>
        },
        {
            title: 'SN码',
            dataIndex: 'sn',
            key: 'sn',
            width: '30%',
            render: (text, record) => {
                const isDuplicate = duplicateSn.includes(text);
                const isInvalidPair = invalidProductPairs.some(item => item.includes(record.id));
                
                return (
                    <Input
                        value={text}
                        onChange={(e) => handleFieldChange(record.key, 'sn', e.target.value)}
                        placeholder="请输入SN码（与站点ID同时填写或同时为空）"
                        maxLength={50}
                        showCount
                        style={{ width: '100%', borderColor: isDuplicate || isInvalidPair ? '#f5222d' : '' }}
                        status={isDuplicate || isInvalidPair ? 'error' : ''}
                    />
                );
            }
        },
        {
            title: '站点ID',
            dataIndex: 'station_id',
            key: 'station_id',
            width: '30%',
            render: (stationId, record) => {
                const isInvalidPair = invalidProductPairs.some(item => item.includes(record.id));
                
                return (
                    <Select
                        value={stationId}
                        onChange={(value) => handleFieldChange(record.key, 'station_id', value)}
                        placeholder="请选择站点（与SN同时填写或同时为空）"
                        style={{ width: '100%', borderColor: isInvalidPair ? '#f5222d' : '' }}
                        status={isInvalidPair ? 'error' : ''}
                        loading={loadingStations}
                    >
                        {stations.length > 0 ? (
                            stations.map(station => (
                                <Option key={station.id} value={station.id}>
                                    {station.id} - {station.name}
                                </Option>
                            ))
                        ) : (
                            <Option value="" disabled>
                                {loadingStations ? '加载中...' : '未找到站点信息'}
                            </Option>
                        )}
                    </Select>
                );
            }
        }
    ];

    // 初始化表单
    useEffect(() => {
        form.setFieldsValue({
            delivery_list_upload_type: 'file',
            factory_acceptance_report_upload_type: 'file',
            shipment_plan_upload_type: 'file',
            product_shipment_order_upload_type: 'file',
            customer_acceptance_report_upload_type: 'file'
        });
    }, [form]);

    // 前往excel导入
    const toExcel = async () => {
        setnowroute({...{route:"/ship/productDelivery/productDeliveryExcelForm",title:"excel导入产品出货订单"}})
    }

    // 处理销售单号搜索 - 获取可选列表
    const handleSalesOrderSearch = useCallback((value) => {
        // 清除之前的计时器
        if (debounceTimer) {
            clearTimeout(debounceTimer);
        }
        
        // 如果输入为空，清空选项
        if (!value || value.trim().length < 1) {
            setSalesOrderOptions([]);
            return;
        }
        
        // 设置新的计时器，延迟500ms执行查询
        const timer = setTimeout(async () => {
            try {
                setLoadingSalesOrders(true);
                
                // 查询匹配的销售订单
                // 修正：移除前端添加的%符号，后端会处理模糊查询
                const data = await request("/admin/sales/searchSales", {
                    method: "POST",
                    body: {
                        condition: { order_id: value }, 
                        pageSize: 20,
                        offset: 0
                    }
                });
                
                if (data.code === 200 && data.data && data.data.length > 0) {
                    // 提取销售单号作为选项（键和值都是销售单号）
                    const options = data.data.map(item => ({
                        value: item.order_id,
                        label: item.order_id
                    }));
                    setSalesOrderOptions(options);
                } else {
                    setSalesOrderOptions([]);
                }
            } catch (error) {
                notification.error({ message: "错误", description: "查询销售订单时发生错误，请重试" });
            } finally {
                setLoadingSalesOrders(false);
            }
        }, 400); // 500ms防抖延迟
        
        setDebounceTimer(timer);
        
        // 组件卸载时清除计时器
        return () => {
            if (timer) clearTimeout(timer);
        };
    }, [debounceTimer]);


    // 处理销售单号选择变化
    const handleSalesOrderSelect = useCallback((value) => {
        // 如果未选择，清空数据
        if (!value) {
            setCompleteProducts([]);
            setIncompleteProducts([]);
            setCustomerName('');
            setDuplicateSn([]);
            setInvalidProductPairs([]);
            setStations([]);
            return;
        }
        
        // 选择后加载相关数据
        const loadSalesOrderData = async () => {
            try {
                setLoadingProducts(true);
                setLoadingCustomer(true);
                setCustomerName('');
                setStations([]);
                
                // 查询销售订单详细信息
                const salesData = await request("/admin/sales/searchSales", {
                    method: "POST",
                    body: {
                        condition: { order_id: value },
                        pageSize: 1,
                        offset: 0,
                        includeCustomer: true
                    }
                });
                
                if (salesData.code === 200 && salesData.data && salesData.data.length > 0) {
                    const salesInfo = salesData.data[0]; // 取第一条匹配的销售订单
                    const { customer_id } = salesInfo;
                    
                    // 查询客户信息
                    if (customer_id) {
                        const customerData = await request("/admin/customer/getCustomers", {
                            method: "POST",
                            body: { id: customer_id }
                        });
                        
                        setCustomerName(customerData.code === 200 && customerData.data 
                            ? customerData.data.name || '未知客户' 
                            : '未找到客户信息');

                        // 查询该客户的站点列表
                        setLoadingStations(true);
                        const stationData = await request("/admin/station/getStations", {
                            method: "POST",
                            body: { 
                                customer_id: customer_id,
                                pageSize: 1000,
                                offset: 0
                            }
                        });
                        
                        if (stationData.code === 200 && stationData.data) {
                            setStations(stationData.data);
                        } else {
                            setStations([]);
                            notification.info({ message: "提示", description: "未查询到该客户的站点信息" });
                        }
                        setLoadingStations(false);
                    } else {
                        setCustomerName('该订单未关联客户');
                        setStations([]);
                    }
                    
                    // 查询销售订单下的产品
                    const productData = await request("/admin/product/getProducts", {
                        method: "POST",
                        body: { sales_order_id: value, pageSize: 1000, offset: 0 }
                    });
                    
                    if (productData.code === 200 && productData.data && productData.data.length > 0) {
                        // 分类产品
                        const completeProducts = productData.data
                            .filter(product => product.sn?.trim() && product.station_id)
                            .map((product, index) => ({
                                key: `complete-${index + 1}`,
                                id: product.id,
                                product_part_number: product.product_part_number || '',
                                specification_and_model: product.specification_and_model || '',
                                sn: product.sn || '',
                                station_id: product.station_id
                            }));
                        
                        const incompleteProducts = productData.data
                            .filter(product => !product.sn?.trim() && !product.station_id)
                            .map((product, index) => ({
                                key: `incomplete-${index + 1}`,
                                id: product.id,
                                product_part_number: product.product_part_number || '',
                                specification_and_model: product.specification_and_model || '',
                                sn: product.sn || '',
                                station_id: product.station_id || ''
                            }));
                        
                        // 过滤异常产品
                        const abnormalProducts = productData.data.filter(
                            product => (product.sn?.trim() && !product.station_id) || (!product.sn?.trim() && product.station_id)
                        );
                        
                        if (abnormalProducts.length > 0) {
                            notification.warning({
                                message: "注意",
                                description: `发现${abnormalProducts.length}个异常产品（SN和站点ID不匹配），已自动过滤`,
                                duration: 5
                            });
                        }
                        
                        setCompleteProducts(completeProducts);
                        setIncompleteProducts(incompleteProducts);
                        checkDuplicateSn(incompleteProducts);
                        checkSnSiteConsistency(incompleteProducts);
                    } else {
                        setCompleteProducts([]);
                        setIncompleteProducts([]);
                        notification.info({ message: "提示", description: "未查询到该销售订单下的产品" });
                    }
                } else {
                    setCompleteProducts([]);
                    setIncompleteProducts([]);
                    notification.info({ message: "提示", description: "未查询到该销售订单信息" });
                }
            } catch (error) {
                notification.error({ message: "错误", description: "查询信息时发生错误，请重试" });
            } finally {
                setLoadingProducts(false);
                setLoadingCustomer(false);
                setLoadingStations(false);
            }
        };
        
        loadSalesOrderData();
    }, [checkDuplicateSn, checkSnSiteConsistency]);

    // 处理字段变化
    const handleFieldChange = (key, fieldName, value) => {
        const newIncompleteProducts = incompleteProducts.map(item => {
            if (item.key === key) {
                const updatedItem = { ...item, [fieldName]: value };
                
                // 保持SN和station_id一致性
                if (fieldName === 'sn' && !value?.trim() && updatedItem.station_id) {
                    updatedItem.station_id = '';
                }
                if (fieldName === 'station_id' && !value && updatedItem.sn?.trim()) {
                    updatedItem.sn = '';
                }
                
                return updatedItem;
            }
            return item;
        });
        
        setIncompleteProducts(newIncompleteProducts);
        checkDuplicateSn(newIncompleteProducts);
        checkSnSiteConsistency(newIncompleteProducts);
    };

    // 文件上传前验证
    const handleBeforeUpload = (fileType) => (file) => {
        const isPDF = file.type === 'application/pdf';
        const isWord = file.type === 'application/msword' || file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        const isLt20M = file.size / 1024 / 1024 < 20;

        if (!isPDF && !isWord && !isExcel) {
            notification.error({ message: '仅支持PDF、Word和Excel文件格式' });
            return false;
        }
        
        if (!isLt20M) {
            notification.error({ message: '文件大小不能超过20MB' });
            return false;
        }

        // 保存文件
        switch(fileType){
            case "delivery_list": setDeliveryListFile(file); break;
            case "factory_acceptance_report": setFactoryAcceptanceReportFile(file); break;
            case "shipment_plan": setShipmentPlanFile(file); break;
            case "product_shipment_order": setProductShipmentOrderFile(file); break;
            case "customer_acceptance_report": setCustomerAcceptanceReportFile(file); break;
        }
        return false;
    }

    // 提交表单
    const submit = async () => {
        try {
            // 验证重复SN
            if (duplicateSn.length > 0) {
                notification.error({
                    message: "提交失败",
                    description: `存在重复的SN码：${duplicateSn.join(', ')}，请修改后再提交`
                });
                return;
            }

            // 验证SN与station_id一致性
            const isConsistent = checkSnSiteConsistency(incompleteProducts);
            if (!isConsistent) {
                notification.error({
                    message: "提交失败",
                    description: `以下产品的SN码与站点ID信息不匹配：${invalidProductPairs.join('; ')}，请修正后再提交`
                });
                return;
            }

            // 筛选已完善信息的产品
            const updatedProducts = incompleteProducts.filter(item => item.sn?.trim() && item.station_id);
            
            // 验证是否有可提交的产品
            if (updatedProducts.length === 0) {
                notification.warning({
                    message: "提示",
                    description: "没有需要上传的产品，请同时填写产品的SN码和站点ID信息"
                });
                return;
            }

            const values = await form.validateFields()
            const formData = new FormData()
            setUploading(true)
            
            // 添加文本字段
            formData.append('shipment_order_id', values.shipment_order_id)
            // 送货地址可能为空，只在有值时添加
            if (values.delivery_address) {
                formData.append('delivery_address', values.delivery_address)
            }
            formData.append('sales_order_id', values.sales_order_id)
            if (values.shipment_date) formData.append('shipment_date', dayjs(values.shipment_date).format('YYYY-MM-DD'))

            // 添加产品数据
            formData.append('products', JSON.stringify(updatedProducts));

            // 添加文件或引用
            if (deliveryListUploadType === 'file' && deliveryListFile) {
                formData.append('delivery_list', deliveryListFile)
            } else if (deliveryListUploadType === 'reference' && values.delivery_list_reference) {
                formData.append('delivery_list_reference', values.delivery_list_reference)
            }

            if (factoryReportUploadType === 'file' && factoryAcceptanceReportFile) {
                formData.append('factory_acceptance_report', factoryAcceptanceReportFile)
            } else if (factoryReportUploadType === 'reference' && values.factory_acceptance_report_reference) {
                formData.append('factory_acceptance_report_reference', values.factory_acceptance_report_reference)
            }

            if (shipmentPlanUploadType === 'file' && shipmentPlanFile) {
                formData.append('shipment_plan', shipmentPlanFile)
            } else if (shipmentPlanUploadType === 'reference' && values.shipment_plan_reference) {
                formData.append('shipment_plan_reference', values.shipment_plan_reference)
            }

            if (productOrderUploadType === 'file' && productShipmentOrderFile) {
                formData.append('product_shipment_order', productShipmentOrderFile)
            } else if (productOrderUploadType === 'reference' && values.product_shipment_order_reference) {
                formData.append('product_shipment_order_reference', values.product_shipment_order_reference)
            }

            if (customerReportUploadType === 'file' && customerAcceptanceReportFile) {
                formData.append('customer_acceptance_report', customerAcceptanceReportFile)
            } else if (customerReportUploadType === 'reference' && values.customer_acceptance_report_reference) {
                formData.append('customer_acceptance_report_reference', values.customer_acceptance_report_reference)
            }

            // 提交数据
            fetch("/admin/productDelivery/uploadOrder", {
                method: "POST",
                body: formData,
                headers:{
                    Authorization: `Bearer ${JSON.parse(localStorage.getItem('user')).token}`
                }
            }).then(response => response.json())
              .then(data => {
                  if(data.code === 200) {
                      notification.success({
                          message: "上传成功",
                          description: `共上传了 ${updatedProducts.length} 个已完善信息的产品`
                      })
                      // 重置表单
                      form.resetFields();
                      setCompleteProducts([]);
                      setIncompleteProducts([]);
                      setCustomerName('');
                      setDuplicateSn([]);
                      setInvalidProductPairs([]);
                      setDeliveryListFile(null);
                      setFactoryAcceptanceReportFile(null);
                      setShipmentPlanFile(null);
                      setProductShipmentOrderFile(null);
                      setCustomerAcceptanceReportFile(null);
                      setSalesOrderOptions([]);
                  } else {
                      notification.error({ message: data.msg || "上传失败" })
                  }
                  setTimeout(()=> setUploading(false), 300)
              })
        } catch (errorInfo) {
            notification.error({ message: "请检查填写信息是否有误" })
            setUploading(false);
        }
    }

    // 标签样式
    const labelStyle = {
        fontSize: '0.9rem',
        fontWeight: 500,
        color: '#333',
        whiteSpace: 'nowrap',
        paddingRight: '8px'
    };

    // 错误提示
    useEffect(() => {
        const messages = [];
        if (duplicateSn.length > 0) {
            messages.push(`发现重复的SN码：${duplicateSn.join(', ')}`);
        }
        if (invalidProductPairs.length > 0) {
            messages.push(`以下产品SN与站点ID信息不匹配：${invalidProductPairs.join('; ')}`);
        }
        
        if (messages.length > 0) {
            notification.warning({
                message: "注意",
                description: messages.join('；'),
                duration: 3
            });
        }
    }, [duplicateSn, invalidProductPairs]);

    return (
        <div style={{ 
            height: "94%", 
            backgroundColor: `#F1F1F1`, 
            right: "1%", 
            top: "4vh", 
            overflow: "hidden",
            width: collapsed ? "94%" : "84%", 
            position: "absolute",  
            color: "white", 
            fontSize: "0.8rem"
        }}>
            <div style={styles.kshcontainer}>
                <div style={{
                    fontSize: "0.7rem", 
                    position: "relative", 
                    width: "96%", 
                    marginLeft: "2%", 
                    display: "flex", 
                    textIndent: "1rem", 
                    justifyContent: "flex-start", 
                    alignContent: "flex-start", 
                    flexWrap: "wrap",
                    maxHeight: "80vh", 
                    overflowY: "auto", 
                    overflowX: "hidden" ,
                    paddingBottom: "2vh"
                }}>
                    <Button type="primary" onClick={toExcel} style={{marginTop:"2vh"}}>
                        <IconFont type="icon-Excel" />通过excel表格导入
                    </Button>
                    
                    {/* 错误提示区域 */}
                    {(duplicateSn.length > 0 || invalidProductPairs.length > 0) && (
                        <div style={{
                            width: '100%',
                            marginTop: '1vh',
                            padding: '8px 12px',
                            backgroundColor: '#fff1f0',
                            border: '1px solid #ffa39e',
                            borderRadius: '4px',
                            color: '#f5222d',
                            fontSize: '0.9rem'
                        }}>
                            {duplicateSn.length > 0 && (
                                <div style={{display: 'flex', alignItems: 'center', marginBottom: '4px'}}>
                                    <IconFont type="icon-warning" style={{ marginRight: '8px' }} />
                                    <span>存在重复的SN码：{duplicateSn.join(', ')}</span>
                                </div>
                            )}
                            {invalidProductPairs.length > 0 && (
                                <div style={{display: 'flex', alignItems: 'center'}}>
                                    <IconFont type="icon-warning" style={{ marginRight: '8px' }} />
                                    <span>SN与站点ID信息不匹配的产品：{invalidProductPairs.join('; ')}（需同时填写或同时为空）</span>
                                </div>
                            )}
                        </div>
                    )}
                    
                    <Divider/>
                    <Form
                        style={{ marginTop: "2vh", width: "95%" }}
                        form={form}
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        labelAlign="right"
                    >
                        {/* 基本信息 */}
                        <Row gutter={24}>
                            <Col span={12}>
                                <Form.Item
                                    label="出货单号"
                                    name="shipment_order_id"
                                    rules={[{ required: true, message: '出货单号不能为空' }]}
                                    labelStyle={labelStyle}
                                >
                                    <Input maxLength={50} showCount placeholder='请输入出货单号' />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label="送货地址"
                                    name="delivery_address"
                                    rules={[{ required: false }]}  // 修改为非必填
                                    labelStyle={labelStyle}
                                >
                                    <Input maxLength={100} showCount placeholder='请输入送货地址（非必填）' />
                                </Form.Item>
                            </Col>
                        </Row>
                        
                        <Row gutter={24}>
                            <Col span={12}>
                                <Form.Item
                                    label="销售单号"
                                    name="sales_order_id"
                                    rules={[{ required: true, message: '请选择销售单号' }]}
                                    labelStyle={labelStyle}
                                >
                                    <Select
                                        showSearch
                                        placeholder="请输入或选择销售单号"
                                        optionFilterProp="children"
                                        loading={loadingSalesOrders}
                                        style={{ width: '100%' }}
                                        onSearch={handleSalesOrderSearch}
                                        onChange={handleSalesOrderSelect}
                                        filterOption={false} // 禁用本地过滤，使用服务器过滤
                                    >
                                        {salesOrderOptions.map(option => (
                                            <Option key={option.value} value={option.value}>
                                                {option.label}
                                            </Option>
                                        ))}
                                    </Select>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label="客户名称"
                                    labelStyle={labelStyle}
                                >
                                    <Spin spinning={loadingCustomer}>
                                        <Input 
                                            value={customerName} 
                                            readOnly 
                                            placeholder="请选择销售单号获取客户信息" 
                                            style={{ backgroundColor: '#f5f5f5' }}
                                        />
                                    </Spin>
                                </Form.Item>
                            </Col>
                        </Row>

                        <Row gutter={24}>
                            <Col span={12}>
                                <Form.Item
                                    label="出货日期"
                                    name="shipment_date"
                                    rules={[{ required: false }]}
                                    labelStyle={labelStyle}
                                >
                                    <DatePicker placeholder='请选择出货日期' />
                                </Form.Item>
                            </Col>
                        </Row>

                        {/* 产品列表 */}
                        <Row gutter={24}>
                            <Col span={24}>
                                <Form.Item
                                    label="已出货产品"
                                    labelStyle={{...labelStyle, display: 'block', marginBottom: '1rem', color: '#1890ff'}}
                                    labelCol={{ span: 24 }}
                                    wrapperCol={{ span: 24 }}
                                >
                                    <div style={{ marginBottom: 16, border: '1px solid #e8e8e8', borderRadius: '4px' }}>
                                        <Spin spinning={loadingProducts}>
                                            <Table
                                                columns={completeProductColumns}
                                                dataSource={completeProducts}
                                                pagination={false}
                                                bordered={false}
                                                locale={{ emptyText: '没有已完善SN码和站点ID信息的产品' }}
                                                scroll={{ x: 'max-content' }}
                                            />
                                        </Spin>
                                    </div>
                                </Form.Item>
                            </Col>
                        </Row>
                        
                        <Row gutter={24}>
                            <Col span={24}>
                                <Form.Item
                                    label="未出货产品"
                                    labelStyle={{...labelStyle, display: 'block', marginBottom: '1rem', color: '#1890ff'}}
                                    labelCol={{ span: 24 }}
                                    wrapperCol={{ span: 24 }}
                                >
                                    <div style={{ marginBottom: 16, border: '1px solid #e8e8e8', borderRadius: '4px' }}>
                                        <Spin spinning={loadingProducts}>
                                            <Table
                                                columns={incompleteProductColumns}
                                                dataSource={incompleteProducts}
                                                pagination={false}
                                                bordered={false}
                                                locale={{ emptyText: '没有需要完善SN码和站点ID信息的产品' }}
                                                scroll={{ x: 'max-content' }}
                                            />
                                        </Spin>
                                    </div>
                                </Form.Item>
                            </Col>
                        </Row>
                        
                        {/* 附件上传 */}
                        <Row>
                            <Col span={24}>
                                <h3 style={{ margin: '16px 0', color: '#1890ff', borderLeft: '3px solid #1890ff', paddingLeft: 12, fontSize: '1.1rem' }}>附件上传</h3>
                            </Col>
                        </Row>
                        
                        {/* 交付清单 */}
                        <Row gutter={24}>
                            <Col span={12}>
                                <Form.Item
                                    label="交付清单上传方式"
                                    name="delivery_list_upload_type"
                                    rules={[{ required: false }]}
                                    labelStyle={labelStyle}
                                >
                                    <Radio.Group 
                                        value={deliveryListUploadType}
                                        onChange={e => setDeliveryListUploadType(e.target.value)}
                                        buttonStyle="solid"
                                        style={{ width: '100%' }}
                                    >
                                        <Radio.Button value="file" icon={<UploadOutlined />} style={{ flex: 1 }}>直接上传文件</Radio.Button>
                                        <Radio.Button value="reference" icon={<LinkOutlined />} style={{ flex: 1 }}>引用单号</Radio.Button>
                                    </Radio.Group>
                                </Form.Item>

                                {deliveryListUploadType === 'file' && (
                                    <Form.Item
                                        label="交付清单清单文件"
                                        name="delivery_list"
                                        rules={[{ required: false }]}
                                        labelStyle={labelStyle}
                                    >
                                        <Upload
                                            maxCount={1}
                                            beforeUpload={handleBeforeUpload('delivery_list')}
                                            onRemove={() => { setDeliveryListFile(null); return true; }}
                                            fileList={deliveryListFile ? [{ uid: deliveryListFile.uid || Date.now().toString(), name: deliveryListFile.name, status: 'done' }] : []}
                                        >
                                            <Button icon={<UploadOutlined />}>选择文件</Button>
                                        </Upload>
                                    </Form.Item>
                                )}

                                {deliveryListUploadType === 'reference' && (
                                    <Form.Item
                                        label="交付清单引用单号"
                                        name="delivery_list_reference"
                                        rules={[{ required: false }]}
                                        labelStyle={labelStyle}
                                    >
                                        <Input maxLength={50} showCount placeholder='请输入要引用的单号' />
                                    </Form.Item>
                                )}
                            </Col>

                            {/* 出厂验收报告 */}
                            <Col span={12}>
                                <Form.Item
                                    label="出厂验收报告上传方式"
                                    name="factory_acceptance_report_upload_type"
                                    rules={[{ required: false }]}
                                    labelStyle={labelStyle}
                                >
                                    <Radio.Group 
                                        value={factoryReportUploadType}
                                        onChange={e => setFactoryReportUploadType(e.target.value)}
                                        buttonStyle="solid"
                                        style={{ width: '100%' }}
                                    >
                                        <Radio.Button value="file" icon={<UploadOutlined />} style={{ flex: 1 }}>直接上传文件</Radio.Button>
                                        <Radio.Button value="reference" icon={<LinkOutlined />} style={{ flex: 1 }}>引用单号</Radio.Button>
                                    </Radio.Group>
                                </Form.Item>

                                {factoryReportUploadType === 'file' && (
                                    <Form.Item
                                        label="出厂验收报告文件"
                                        name="factory_acceptance_report"
                                        rules={[{ required: false }]}
                                        labelStyle={labelStyle}
                                    >
                                        <Upload
                                            maxCount={1}
                                            beforeUpload={handleBeforeUpload('factory_acceptance_report')}
                                            onRemove={() => { setFactoryAcceptanceReportFile(null); return true; }}
                                            fileList={factoryAcceptanceReportFile ? [{ uid: factoryAcceptanceReportFile.uid || Date.now().toString(), name: factoryAcceptanceReportFile.name, status: 'done' }] : []}
                                        >
                                            <Button icon={<UploadOutlined />}>选择文件</Button>
                                        </Upload>
                                    </Form.Item>
                                )}

                                {factoryReportUploadType === 'reference' && (
                                    <Form.Item
                                        label="出厂验收报告引用单号"
                                        name="factory_acceptance_report_reference"
                                        rules={[{ required: false }]}
                                        labelStyle={labelStyle}
                                    >
                                        <Input maxLength={50} showCount placeholder='请输入要引用的单号' />
                                    </Form.Item>
                                )}
                            </Col>
                        </Row>
                        
                        {/* 出货计划和产品出货单 */}
                        <Row gutter={24}>
                            <Col span={12}>
                                <Form.Item
                                    label="出货计划上传方式"
                                    name="shipment_plan_upload_type"
                                    rules={[{ required: false }]}
                                    labelStyle={labelStyle}
                                >
                                    <Radio.Group 
                                        value={shipmentPlanUploadType}
                                        onChange={e => setShipmentPlanUploadType(e.target.value)}
                                        buttonStyle="solid"
                                        style={{ width: '100%' }}
                                    >
                                        <Radio.Button value="file" icon={<UploadOutlined />} style={{ flex: 1 }}>直接上传文件</Radio.Button>
                                        <Radio.Button value="reference" icon={<LinkOutlined />} style={{ flex: 1 }}>引用单号</Radio.Button>
                                    </Radio.Group>
                                </Form.Item>

                                {shipmentPlanUploadType === 'file' && (
                                    <Form.Item
                                        label="出货计划文件"
                                        name="shipment_plan"
                                        rules={[{ required: false }]}
                                        labelStyle={labelStyle}
                                    >
                                        <Upload
                                            maxCount={1}
                                            beforeUpload={handleBeforeUpload('shipment_plan')}
                                            onRemove={() => { setShipmentPlanFile(null); return true; }}
                                            fileList={shipmentPlanFile ? [{ uid: shipmentPlanFile.uid || Date.now().toString(), name: shipmentPlanFile.name, status: 'done' }] : []}
                                        >
                                            <Button icon={<UploadOutlined />}>选择文件</Button>
                                        </Upload>
                                    </Form.Item>
                                )}

                                {shipmentPlanUploadType === 'reference' && (
                                    <Form.Item
                                        label="出货计划引用单号"
                                        name="shipment_plan_reference"
                                        rules={[{ required: false }]}
                                        labelStyle={labelStyle}
                                    >
                                        <Input maxLength={50} showCount placeholder='请输入要引用的单号' />
                                    </Form.Item>
                                )}
                            </Col>

                            <Col span={12}>
                                <Form.Item
                                    label="产品出货单上传方式"
                                    name="product_shipment_order_upload_type"
                                    rules={[{ required: false }]}
                                    labelStyle={labelStyle}
                                >
                                    <Radio.Group 
                                        value={productOrderUploadType}
                                        onChange={e => setProductOrderUploadType(e.target.value)}
                                        buttonStyle="solid"
                                        style={{ width: '100%' }}
                                    >
                                        <Radio.Button value="file" icon={<UploadOutlined />} style={{ flex: 1 }}>直接上传文件</Radio.Button>
                                        <Radio.Button value="reference" icon={<LinkOutlined />} style={{ flex: 1 }}>引用单号</Radio.Button>
                                    </Radio.Group>
                                </Form.Item>

                                {productOrderUploadType === 'file' && (
                                    <Form.Item
                                        label="产品出货单文件"
                                        name="product_shipment_order"
                                        rules={[{ required: false }]}
                                        labelStyle={labelStyle}
                                    >
                                        <Upload
                                            maxCount={1}
                                            beforeUpload={handleBeforeUpload('product_shipment_order')}
                                            onRemove={() => { setProductShipmentOrderFile(null); return true; }}
                                            fileList={productShipmentOrderFile ? [{ uid: productShipmentOrderFile.uid || Date.now().toString(), name: productShipmentOrderFile.name, status: 'done' }] : []}
                                        >
                                            <Button icon={<UploadOutlined />}>选择文件</Button>
                                        </Upload>
                                    </Form.Item>
                                )}

                                {productOrderUploadType === 'reference' && (
                                    <Form.Item
                                        label="产品出货单引用单号"
                                        name="product_shipment_order_reference"
                                        rules={[{ required: false }]}
                                        labelStyle={labelStyle}
                                    >
                                        <Input maxLength={50} showCount placeholder='请输入要引用的单号' />
                                    </Form.Item>
                                )}
                            </Col>
                        </Row>
                        
                        {/* 客户验收报告 */}
                        <Row gutter={24}>
                            <Col span={12}>
                                <Form.Item
                                    label="客户验收报告上传方式"
                                    name="customer_acceptance_report_upload_type"
                                    rules={[{ required: false }]}
                                    labelStyle={labelStyle}
                                >
                                    <Radio.Group 
                                        value={customerReportUploadType}
                                        onChange={e => setCustomerReportUploadType(e.target.value)}
                                        buttonStyle="solid"
                                        style={{ width: '100%' }}
                                    >
                                        <Radio.Button value="file" icon={<UploadOutlined />} style={{ flex: 1 }}>直接上传文件</Radio.Button>
                                        <Radio.Button value="reference" icon={<LinkOutlined />} style={{ flex: 1 }}>引用单号</Radio.Button>
                                    </Radio.Group>
                                </Form.Item>

                                {customerReportUploadType === 'file' && (
                                    <Form.Item
                                        label="客户验收报告文件"
                                        name="customer_acceptance_report"
                                        rules={[{ required: false }]}
                                        labelStyle={labelStyle}
                                    >
                                        <Upload
                                            maxCount={1}
                                            beforeUpload={handleBeforeUpload('customer_acceptance_report')}
                                            onRemove={() => { setCustomerAcceptanceReportFile(null); return true; }}
                                            fileList={customerAcceptanceReportFile ? [{ uid: customerAcceptanceReportFile.uid || Date.now().toString(), name: customerAcceptanceReportFile.name, status: 'done' }] : []}
                                        >
                                            <Button icon={<UploadOutlined />}>选择文件</Button>
                                        </Upload>
                                    </Form.Item>
                                )}

                                {customerReportUploadType === 'reference' && (
                                    <Form.Item
                                        label="客户验收报告引用单号"
                                        name="customer_acceptance_report_reference"
                                        rules={[{ required: false }]}
                                        labelStyle={labelStyle}
                                    >
                                        <Input maxLength={50} showCount placeholder='请输入要引用的单号' />
                                    </Form.Item>
                                )}
                            </Col>
                        </Row>
                        
                        {/* 提交按钮 */}
                        <Row>
                            <Col span={24} style={{ marginTop: 16 }}>
                                <Button type="primary" onClick={submit}>提交订单</Button>
                            </Col>
                        </Row>
                    </Form>
                    
                    {/* 上传加载框 */}
                    <Modal
                        open={uploading}
                        centered
                        closable={false}
                        footer={null}
                        maskClosable={false}
                        width={400}
                        bodyStyle={{ textAlign: 'center', padding: '30px 20px' }}
                    >
                        <Spin/>
                        <div style={{ marginTop: 20, fontSize: 16, fontWeight: 'bold', color: '#333' }}>上传中</div>
                        <div style={{ marginTop: 10, color: '#666' }}>请勿关闭页面或进行其他操作</div>
                    </Modal>
                </div>
            </div>
        </div>
    )
}

export default ProductDeliveryUploadOrder

// 样式定义
const styles = {
    kshcontainer: {
        width: "98%", 
        height: "95%", 
        position: "absolute", 
        top: "3%", 
        left: "1%", 
        backgroundColor: "white", 
        color: "black",
        borderRadius: "10px",
    },
}
